<template>
  <el-upload
    v-model:file-list="fileList"
    class="upload-demo"
    action="#"
    :accept="accept"
    :auto-upload="false"
    :limit="1"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :on-change="beforeUpload"
    :on-exceed="handleExceed"
  >
    <template #trigger>
      <el-button type="primary">选择文件</el-button>
    </template>
    <el-button style="margin-left: 10px" type="success" @click="submitUpload">
      上传文件
    </el-button>
    <el-button style="margin-left: 10px" type="success" @click="test">
      测试
    </el-button>
  </el-upload>
</template>

<script setup>
import { ref, defineProps, watch, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'
import { uploadFiles } from '@/api/multimedia/multimediaList.js'

const props = defineProps({
  name: String,
  open: Boolean
})
const fileList = ref([])
const accept = ref('')
const emits = defineEmits()

watch(
  () => props.name,
  (newValue) => {
    if (newValue === 'picture') {
      accept.value = '.jpg,.png,.jpeg'
    } else if (newValue === 'video') {
      accept.value = '.mp4'
    } else if (newValue === 'audio') {
      accept.value = '.mp3'
    } else if (newValue === 'word') {
      accept.value = '.doc,.docx'
    } else if (newValue === 'excel') {
      accept.value = '.xls,.xlsx'
    }
  },
  { immediate: true }
)

watch(
  () => props.open,
  (newValue) => {
    if (newValue === true) {
      fileList.value = []
    }
  },
  { immediate: true }
)
const test = () => {
  console.log('test', fileList.value)
}
// 文件预览
const handlePreview = (uploadFile) => {
  console.log('uploadFile', uploadFile)
}
// 文件删除
const handleRemove = (file, uploadFiles) => {
  console.log(file, uploadFiles)
}

const beforeUpload = (file) => {
  const typeArray = accept.value.split(',') || []
  const type = file.name.substring(file.name.lastIndexOf('.'))
  fileList.value.push(file)
  emits('handleFileList', fileList.value)
  if (!typeArray.includes(type)) {
    ElMessage.error(`只能上传${accept.value}格式的文件`)
    fileList.value = []
    return false
  }
  if (file.size / 1024 / 1024 > 500) {
    ElMessage.error('文件大小不能超过500M')
    fileList.value = []
    return false
  }
}

// 文件超出限制时触发
const handleExceed = (files, fileList) => {
  fileList.value = [files[0]]
}

const submitUpload = () => {
  const formData = new FormData()
  fileList.value.forEach(async (file) => {
    if (file.raw) {
      formData.append('file', file.raw)
      formData.append('filename', file.name)
      formData.append('userld', '1')
    }
    await uploadFiles(formData).then((res) => {
      if (res.success) {
        ElMessage.success('文件导入成功')
        fileList.value = []
      } else {
        ElMessage.error('文件导入失败')
      }
    })
  })
}
</script>
